import functools
import logging
import os
import time
from logging.handlers import TimedRotatingFileHandler
from tkinter import Text, END


class TextHandler(logging.Handler):
    def __init__(self, text_widget: Text):
        super().__init__()
        self.text_widget = text_widget

    def emit(self, record):
        msg = self.format(record)
        self.text_widget.after(0, self.text_widget.insert, END, msg + '\n')
        self.text_widget.after(0, self.text_widget.see, END)  # 自动滚动到底部


class SafeFormatter(logging.Formatter):
    def format(self, record):
        if not hasattr(record, "pk"):
            record.pk = "anonymous"
        else:
            try:
                if len(record.pk.split("-")) > 1:
                    record.pk = "-".join(record.pk.split("-")[1:])
            except:
                pass
        return super().format(record)


class LeLogger:
    format_str = "%(asctime)s - %(pk)s - %(message)s"

    def __init__(self,
                 name: str,
                 log_dir: str = "./logs",
                 level: int = logging.INFO,
                 when: str = "midnight",
                 backup_count: int = 7,
                 fmt: str = None):
        """
        初始化日志配置

        :param name: logger 名称（建议使用 __name__）
        :param log_dir: 日志目录
        :param level: 日志级别
        :param when: 日志分割策略，默认按天（midnight）
        :param backup_count: 保留的旧日志文件数量
        :param fmt: 日志格式
        """
        self.name = name
        self.log_dir = log_dir
        self.level = level
        self.when = when
        self.backup_count = backup_count
        self.format = fmt if fmt else self.format_str
        self.logger = self._setup_logger()

    def _setup_logger(self) -> logging.Logger:
        os.makedirs(self.log_dir, exist_ok=True)
        logger = logging.getLogger(self.name)
        logger.setLevel(self.level)

        if logger.handlers:
            return logger  # 避免重复添加 handler

        formatter = SafeFormatter(self.format)

        # 控制台 Handler
        console_handler = logging.StreamHandler()
        console_handler.setFormatter(formatter)
        logger.addHandler(console_handler)

        # 文件 Handler（按天切割）
        log_file = os.path.join(self.log_dir, f"{self.name}.log")
        file_handler = TimedRotatingFileHandler(log_file, when=self.when, backupCount=self.backup_count,
                                                encoding='utf-8')
        file_handler.setFormatter(formatter)
        logger.addHandler(file_handler)

        return logger

    def get_logger(self) -> logging.Logger:
        return self.logger

    @staticmethod
    def add_text_handler(logger, text_widget: Text):
        formatter = SafeFormatter(LeLogger.format_str)
        text_handler = TextHandler(text_widget)
        text_handler.setFormatter(formatter)
        logger.addHandler(text_handler)



log: logging.Logger = LeLogger(__name__).get_logger()


def log_decorator(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        s_time = time.time()
        result = func(*args, **kwargs)
        # log.info(f"调用 {func.__name__}，参数: {args}, {kwargs}, 返回值: {result}")
        log.info(f"调用 {func.__name__} 耗时：{time.time()-s_time} 秒")
        return result
    return wrapper